//  service/tags.js
"use strict";
const Service = require("egg").Service;
class TagsService extends Service {
  // 创建标签
  async newTags(data) {
    const { app } = this;
    try {
      const result = await app.mysql.insert("tags", data);
      return result;
    } catch (error) {
      console.log(error);
      return null;
    }
  }
  // 删除标签
  async deleteTags(id) {
    const { app } = this;
    try {
      const result = await app.mysql.delete("tags", { id: id });
      return result;
    } catch (error) {
      console.log(error);
      return null;
    }
  }
  // 更新标签
  async updateTags(data) {
    const { app } = this;
    try {
      const result = await app.mysql.update("tags", data);
      return result;
    } catch (error) {
      console.log(error);
      return null;
    }
  }
  // 标签列表
  async getTagsList(data) {
    const { app } = this;
    try {
      let sql = "SELECT * FROM tags";
      const content = []; // 参数
      let isMore = false; // 是否有多个查询参数,只用于搜索查询
      // 搜索：id/名字
      if (data.keyword) {
        sql += " WHERE CONCAT(id,name) like ?";
        content.push("%" + data.keyword + "%");
        isMore = true;
      }
      // 状态
      if (data.status != "" && data.status != null && data.status != undefined) {
        if (isMore) {
          sql += "AND status == ?";
        } else {
          sql += " WHERE status == ?";
        }
        content.push(data.status);
        isMore = true;
      }
      // 创建时间
      if (data.begin && data.end) {
        if (isMore) {
          sql += "AND create_time BETWEEN ? AND ?";
        } else {
          sql += " WHERE create_time BETWEEN ? AND ?";
        }
        content.push(data.begin, data.end);
        isMore = true;
      }
      // 开启分页
      if (data.pageNo && data.pageSize) {
        const pageNo = data.pageNo; // 当前页码
        const pageSize = data.pageSize; // 一页展示多少条数据
        sql += " LIMIT ?,?";
        content.push(parseInt((pageNo - 1) * pageSize), parseInt(pageSize));
      }
      const res = {
        code: 200,
        page: data.pageNo,
        pageSize: data.pageSize,
        data: [],
        total: "",
      };
      res.data = await this.app.mysql.query(sql, content);
      res.total = await this.app.mysql.count("tags");
      return res;
    } catch (error) {
      console.log(error);
      return null;
    }
  }
  // 标签详情
  async getTagsDetail(id) {
    const { app } = this;
    try {
      const result = await app.mysql.get("tags", { id: id });
      return result;
    } catch (error) {
      console.log(error);
      return null;
    }
  }
}
module.exports = TagsService;
